﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using LLoger;
using OpenPop.Mime;
using TSRepLoader.Pop;
using TSRepLoader.Properties;
using OpenPop.Mime.Header;

namespace TSRepLoader
{
    public class FortsDownloader : MailDownloader
    {
        private readonly Settings _sett = Properties.Settings.Default;

        public FortsDownloader(string host, int port, string user, string pass, ILogWriter log) :
            base(host, port, false, user, pass, log)
        {
            CheckAndCreatePath(_sett.FortsRepPath);
        }

        public override void Load(DateTime date)
        {
            var subjs = _sett.FortsSubject.Split(';');
            if (subjs.Length == 1)
            {
                Load(date, null, _sett.FortsSubject, _sett.FortsSign);
                return;
            }

            if (subjs.Length > 1)
            {
                foreach (var subj in subjs)

                    Load(date, null, subj, _sett.FortsSign);

                return;
            }

            _log.WriteLine("ERROR: Necessary mails not found");
        }

        /// <summary>
        ////Сохранение и переименование зип-архива
        /// </summary>
        /// <param name="savedFile"></param>
        /// <returns></returns>
        protected override bool HandleAttachment(string savedFile, MessageHeader subject = null)
        {
            if (!File.Exists(savedFile))
            {
                _log.WriteLine("ERROR: Attachment file was not found " + savedFile);
                return false;
            }

            string path = Path.Combine(_sett.FortsRepPath, LoadDate.ToString("yyyy"),
                LoadDate.ToString("MM"));

            CheckAndCreatePath(path);

            string fName;//= LoadDate.ToString("yyyyMMdd") + Path.GetExtension(savedFile);
            fName = Path.GetFileName(savedFile);
            fName = GetIncFileName(path, fName);

            path = Path.Combine(path, fName);

            File.Copy(savedFile, path);

            _log.WriteLine("Attachement was saved to final path " + path);

            return true;
        }


        protected override string SaveToFile(MessagePart attachment, MessageHeader hdr = null)
        {
            try
            {
                var fileName = (hdr == null || string.IsNullOrWhiteSpace(hdr.Subject)) ? attachment.FileName : hdr.Subject;
                fileName += Path.GetExtension(attachment.FileName);
                string path = GetIncFileName(DownloadFolder, fileName);
                //Path.Combine(DownloadFolder, attachment.FileName);
                attachment.Save(new FileInfo(path));

                return path;
            }
            catch (Exception ex)
            {
                _log.WriteLine(ex, "ERROR: Unaable to save attachment file");
            }

            return "";
        }

        private string GetIncFileName(string path, string fileName)
        {
            string res = fileName;
            int i = 2;
            foreach (var file in Directory.EnumerateFiles(path))
            {
                if (Path.GetFileName(file) == fileName)
                {
                    res = Path.GetFileNameWithoutExtension(fileName) + "_" + (i) + Path.GetExtension(fileName);
                    res = GetIncFileName(path, res);
                    break;
                }
            }

            return Path.Combine(path, res);
        }
    }
}
